﻿using System;
using System.IO;
using System.IO.Packaging;
using System.Text;

namespace MC.EventHandler.Package
{
    class Program
    {
        private static string _roothPath;

        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: Package.exe <Root_Path");
                Console.WriteLine("Press Any Key to Continue");
                Console.ReadKey();
                return;
            }
            _roothPath = args[0];
            if (!_roothPath.EndsWith(@"\"))
            {
                _roothPath += @"\";
            }
            //TODO: Copy the necessary files to a Package Directory
            var packageDirectory = _roothPath + @"Package\";
            Directory.CreateDirectory(packageDirectory);
            CopyDirectory(_roothPath + @"EventHandler.UI\", packageDirectory + @"Web\");
            CopyDirectory(_roothPath + @"SQL\", packageDirectory + @"SQL\");
            var SQLFiles = new StringBuilder();
            foreach(var file in Directory.GetFiles(packageDirectory + @"SQL\"))
            {
                SQLFiles.Append(" -i \"");
                SQLFiles.Append(file);
                SQLFiles.Append("\"");
            }
            using(var sw = File.CreateText(packageDirectory + @"SQL\InstallDB.bat"))
            {
                sw.WriteLine(@"sqlcmd -U %1 -P %2 -S %3 {0}", SQLFiles);

                sw.Close();
            }
            CopyDirectory(_roothPath + @"Install\MC.EventHandler.Install\bin\Release\", packageDirectory );
            //TODO: Zip up the necessary Files
            ZipUtil.ZipFiles(packageDirectory, _roothPath + "MC.EventHandler.Zip", null);
        }

        public static void CopyDirectory(string Src, string Dst)
        {
            if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar)
                Dst += Path.DirectorySeparatorChar;
            if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
            string[] Files = Directory.GetFileSystemEntries(Src);
            foreach (string Element in Files)
            {
                // Sub directories

                if (Directory.Exists(Element))
                    CopyDirectory(Element, Dst + Path.GetFileName(Element));
                // Files in directory

                else
                    File.Copy(Element, Dst + Path.GetFileName(Element), true);
            }
        }

    }
}
